package cn.jinjimi.app.main.activity;

import android.content.pm.ActivityInfo;
import android.media.MediaPlayer;
import android.net.NetworkInfo;
import android.net.Uri;
import android.os.Handler;
import android.view.View;
import android.view.WindowManager;
import android.widget.ImageButton;
import android.widget.ProgressBar;
import android.widget.RelativeLayout;
import android.widget.TextView;

import cn.jinjimi.app.R;
import cn.jinjimi.app.bean.BundleKey;
import cn.jinjimi.app.entity.VideoInfo;
import cn.jinjimi.app.main.dialog.CommAlertDialog;
import cn.jinjimi.app.main.extend.BaseActivity;
import cn.jinjimi.app.main.uicontroller.MyMediaController;
import cn.jinjimi.app.main.widget.MyVideoView;

/**
 * Created by Roy
 * Date: 15/11/27
 */
public class VideoActivity extends BaseActivity implements View.OnClickListener, MediaPlayer.OnPreparedListener,
        MediaPlayer.OnCompletionListener, MediaPlayer.OnErrorListener,
        MyMediaController.ShowStateChangeListener {

    private VideoInfo videoInfo;
    private MyVideoView mVideoView;
    private MyMediaController mediaController;

    private RelativeLayout rlTop;

    private ProgressBar pb;
    private ImageButton btnStar;

    private int mPositionWhenPaused;

    final Handler handler = new Handler();

    int old_duration;
    Runnable runnable = new Runnable() {
        public void run() {
            int duration = mVideoView.getCurrentPosition();
            if (old_duration == duration && mVideoView.isPlaying()) {
                pb.setVisibility(View.VISIBLE);
            } else {
                pb.setVisibility(View.GONE);
                btnStar.setVisibility(View.GONE);
            }
            old_duration = duration;

            if (!mVideoView.isPlaying()) {
                btnStar.setVisibility(View.VISIBLE);
            }

            if (!isNetworkAvailable() && mVideoView.getDuration() * mVideoView.getBufferPercentage() / 100 - mVideoView.getCurrentPosition() < 2000) {
                videoPause();
                mVideoView.setForbiddenStart(true);
            } else {
                mVideoView.setForbiddenStart(false);
            }

            handler.postDelayed(runnable, 500);
        }
    };

    @Override
    protected void beforeInitView() {
        /* 设置屏幕常亮 *//* flag：标记 ； */
        getWindow().addFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON);
        /* 设置全屏 */
        setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE);

        videoInfo = (VideoInfo) getIntent().getSerializableExtra(BundleKey.PARAM_VIDEOINFO);
        setContentView(R.layout.activity_video);

    }

    @Override
    protected void initial() {
        initView();
        initListener();
        initData();
    }

    protected void initView() {
        mVideoView = (MyVideoView) findViewById(R.id.surface_view);
        ((TextView) findViewById(R.id.tv_title)).setText(videoInfo.title);
        rlTop = (RelativeLayout) findViewById(R.id.top_bar);

        mediaController = new MyMediaController(this);

        pb = (ProgressBar) findViewById(R.id.probar);
        btnStar = (ImageButton) findViewById(R.id.btn_start);
    }

    protected void initListener() {
        findViewById(R.id.btn_back).setOnClickListener(this);
        mVideoView.setOnPreparedListener(this);
        mVideoView.setOnCompletionListener(this);
        mVideoView.setOnErrorListener(this);

        mediaController.setShowStateChangeListener(this);
        btnStar.setOnClickListener(this);
    }

    protected void initData() {
        if (null != videoInfo) {
            mVideoView.setVideoURI(Uri.parse(videoInfo.videoUrl));
            mVideoView.setMediaController(mediaController);
            mVideoView.requestFocus();
        }
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.btn_back:
                finish();
                break;
            case R.id.btn_start:
                videoStart();
                break;
        }
    }

    /* 视频播放完成后回调 */
    @Override
    public void onCompletion(MediaPlayer mp) {
        mVideoView.seekTo(0);
        videoPause();
    }

    /* 异步操作调用过程中发生错误时调用 */
    @Override
    public boolean onError(MediaPlayer mp, int what, int extra) {
        switch (what) {
            case MediaPlayer.MEDIA_ERROR_UNKNOWN:
                break;
            case MediaPlayer.MEDIA_ERROR_SERVER_DIED:
                break;
        }

        switch (extra) {
            case MediaPlayer.MEDIA_ERROR_IO:
                break;
            case MediaPlayer.MEDIA_ERROR_MALFORMED:
                break;
            case MediaPlayer.MEDIA_ERROR_UNSUPPORTED:
                break;
            case MediaPlayer.MEDIA_ERROR_TIMED_OUT:
                break;
        }
        if (!isNetworkAvailable()) {
            videoPause();
            getAlertDialog().setTitle("无法连接网络，请稍后重试").showDialog(CommAlertDialog.Style.ONE_BUTTON);
        } else
            showFinishDialog();
        return true;
    }

    private void showFinishDialog() {
        getAlertDialog().setTitle("无法播放该视频").setRightBtn(getString(R.string.ok), new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                getAlertDialog().dismissDialog();
                finish();
            }
        });
        getAlertDialog().setCanceledOnTouchOutside(false);
        getAlertDialog().showDialog(CommAlertDialog.Style.ONE_BUTTON);
    }

    /* 视频预处理完成后回调 */
    @Override
    public void onPrepared(MediaPlayer mediaPlayer) {
        pb.setVisibility(View.GONE);
        videoStart();
        hideTop();

        mediaPlayer.setOnInfoListener(new MediaPlayer.OnInfoListener() {
            @Override
            public boolean onInfo(MediaPlayer mp, int what, int extra) {
                if (what == MediaPlayer.MEDIA_INFO_BUFFERING_START)
                    pb.setVisibility(View.VISIBLE);
                if (what == MediaPlayer.MEDIA_INFO_BUFFERING_END)
                    pb.setVisibility(View.GONE);
                return false;
            }
        });

//        mediaPlayer.setOnBufferingUpdateListener(new MediaPlayer.OnBufferingUpdateListener() {
//            @Override
//            public void onBufferingUpdate(MediaPlayer mp, int percent) {
//            }
//        });
    }

    @Override
    public void onShown() {
        showTop();
    }

    @Override
    public void onHidden() {
        hideTop();
    }

    public void hideTop() {
        rlTop.setVisibility(View.GONE);
    }

    public void showTop() {
        rlTop.setVisibility(View.VISIBLE);
    }

    private void videoStart() {
        if (mVideoView != null) {
            if (mVideoView.checkCanStart() || isNetworkAvailable()) {
                mVideoView.start();
                btnStar.setVisibility(View.GONE);
                handler.removeCallbacks(runnable);
                handler.postDelayed(runnable, 1000);
            }
        }
    }

    private void videoPause() {
        if (mVideoView != null) {
            mVideoView.pause();
            mPositionWhenPaused = mVideoView.getCurrentPosition();
            btnStar.setVisibility(View.VISIBLE);
        }
    }

    private void videoResume() {
        if (mPositionWhenPaused > 0) {
            mVideoView.seekTo(mPositionWhenPaused);
            mPositionWhenPaused = -1;
        }
    }


    @Override
    protected void onNetworkUnavailable() {
        super.onNetworkUnavailable();
        mVideoView.setNetAvaliable(false);
    }

    @Override
    protected void onNetworkAvailable(NetworkInfo ni) {
        super.onNetworkAvailable(ni);
        mVideoView.setNetAvaliable(true);
        mVideoView.setForbiddenStart(false);
    }

    @Override
    protected void onResume() {
        super.onResume();
        videoResume();
    }

    @Override
    protected void onPause() {
        super.onPause();
        videoPause();
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        handler.removeCallbacks(runnable);
    }
}
